var TeacherInfoDlg = {
    width: '650px',
    height: 'auto',
    currentLayerIndex: -1,
    cache: ""
};

/**
 * 初始化新增弹出框
 */
TeacherInfoDlg.init = function () {
    this.cache = $("#teacherInfoDialog").html();
    $("#teacherInfoDialog").html('');
};

/**
 * 关闭此对话框
 */
TeacherInfoDlg.close = function () {
    layer.close(this.currentLayerIndex);
};

/**
 * 打开模态框调用事件
 * 初始化
 */
TeacherInfoDlg.renderAdd = function () {
    //初始化
    //初始化省、图片上传
    TeacherInfoDlg.province();
    TeacherInfoDlg.initUploadImg();
};

//获取省
TeacherInfoDlg.province = function () {
    var ajax = new $ax(Feng.ctxPath+"/province/getProvinceList", function(data){
        Feng.log("省查询成功");
        var obj = data.obj || [];
        if (obj.length>0){
            $("#provinceId").html("<option value=''>--请选择省--</option>");
            var selectItem = "";
            for(var i=0,len=obj.length; i<len; i++){
                selectItem+="<option value='{0}'>{1}</option>".format(obj[i].id,obj[i].name);
            }
            $("#provinceId").append(selectItem);
        }
    },function(data){
        Feng.error("省查询失败!");
    });
    ajax.start();
};

//选择省获取市
$("#provinceId").on("change",function () {
    var selectItem = "<option value=''>--请选择市--</option>";
    if($(this).val() !== ""){
        var ajax = new $ax(Feng.ctxPath+"/province/selectLocByProvinceId", function(data){
            Feng.log("市查询成功");
            var obj = data.obj || [];
            if (obj.length>0){

                for(var i=0,len=obj.length; i<len; i++){
                    selectItem+="<option value='{0}'>{1}</option>".format(obj[i].id,obj[i].city);
                }
                $("#location").html(selectItem);
            }
        },function(data){
            Feng.error("市查询失败!");
        });
        ajax.data={provinceId:$(this).val()};
        ajax.start();
    }
    else{
        $("#location").html(selectItem);
    }
});

//切换教师类别 控制 显示隐藏 所属机构
$('#roleId').change(function () {
    var roleId = $(this).children('option:selected').val();//这就是selected的值
    if (roleId === "2") {
        // $("#organizationDiv").removeClass("hide").show();
        $("#organizationDiv").show();
    } else {
        // $("#organizationDiv").addClass("hide").hide();
        $("#organizationDiv").hide();
    }

});

//查询教师详情
TeacherInfoDlg.teacherDetail = function (id) {
    var ajax = new $ax(Feng.ctxPath+"/teacher/getById", function(data){
        Feng.log("查询详情成功");
        if (data.success){
            var cityList = data.obj.city || [],
                teacher = data.obj.teacher,
                provinceList = data.obj.province || [];

            //获取省
            $("#provinceId").html("");
            var provinceHtml = "<option value=''>--请选择省--</option>";
            if (provinceList.length>0){
                for(var i=0,len=provinceList.length; i<len; i++){
                    provinceHtml+="<option value='{0}'>{1}</option>".format(provinceList[i].id,provinceList[i].name);
                }
                $("#provinceId").html(provinceHtml);
            }

            //获取市
            var cityHtml = "<option value=''>--请选择市--</option>";
            if (cityList.length>0){
                for(var i=0,len=cityList.length; i<len; i++){
                    cityHtml+="<option value='{0}'>{1}</option>".format(cityList[i].id,cityList[i].city);
                }
                
            }
            $("#location").html(cityHtml);

            //显示图片
            if (teacher.teacherImg !== null) {
                var picHtml = "<div class='item col-md-2 thumbnail' style='background-image:url(" + Feng.ctxPath + "//file/getImage/" + teacher.teacherImg + ");'>" +
                    "<a class=\"btn-close glyphicon glyphicon-remove\" data-name='" + teacher.teacherImg + "'></a>" +
                    "</div>";
                $("#img_list").html(picHtml);
            }
            TeacherInfoDlg.displayUploadBtn();
            //显示教师数据
            for (var i in teacher){
                //判断Id与name是否相同
                if ($("#" + i).attr("name") == i) {
                    $("#" + i).val(teacher[i]);
                }
            }
        }
    },function(data){
        Feng.error("查询详情失败!");
    });
    ajax.set("id",id);
    ajax.start();
};

/**
 * 修改教师详细信息
 */
TeacherInfoDlg.editSubmit = function () {
    var options = getFormJson("#frmMainInfo");
    //添加图片
    var fileObj = {};
    var countIndex = $(".nav-tabs .active").index();
    if(countIndex===0)
        fileObj = TeacherInfoDlg.getUploadImgName();
    else{}

    if(JSON.stringify(fileObj)!=="{}"){
        options = $.extend(options,fileObj);
    }
    var ajax = new $ax(Feng.ctxPath+"/teacher/update", function(data){
        if (data.success === true) {
            Feng.success("修改成功!");
            TeacherTable.me.refresh();
            // backTeacherListPage();
        } else if (data.code === 2) {
            Feng.error(data.msg);
        } else {
            Feng.error("修改失败!");
        }
    },function(data){
        Feng.error("修改失败!");
    });
    ajax.setData(options);
    ajax.start();
}

//保存教师信息
$("#btn-save").on("click",function () {
    var options = getFormJson("#frmMainInfo");
    //添加图片
    var fileObj = {};
    var countIndex = $(".nav-tabs .active").index();
    if(countIndex===0)
        fileObj = TeacherInfoDlg.getUploadImgName();
    else{}

    if(JSON.stringify(fileObj)!=="{}"){
        options = $.extend(options,fileObj);
    }
    var ajax = new $ax(Feng.ctxPath + "/teacher/save", function (data) {
        if (data.success === true) {
            Feng.success("新增成功!");
            // backTeacherListPage();
        } else if (data.code === 2) {
            Feng.error(data.msg);
        } else {
            Feng.error("新增失败!");
        }
    },function(data){
        Feng.error("新增失败!");
    });
    ajax.setData(options);
    ajax.start();
});

//获取上传图片名称
TeacherInfoDlg.getUploadImgName = function () {
    var imgName = {};
    $("#img_list .btn-close").each(function (index) {
        var pictureName = $(this).attr("data-name");
        var index = parseInt(index)+1;
        imgName["picture"+index] = pictureName;
    });
    return imgName;
};

//图片上传
TeacherInfoDlg.initUploadImg = function () {

    $("#file").uploadify({
        height        : 30,
        swf           : Feng.ctxPath+'/js/assets/lib/uploadify/uploadify.swf?ver='+Math.random(),
        uploader      : Feng.ctxPath+'/file/upload?ver='+Math.random(),
        width         : 120,
        fileObjName   : 'file',
        fileTypeExts: '*.jpg;*.jpeg;*.png;*.gif;', //文件后缀限制 默认：'*.
        fileSizeLimit: '3MB', //文件大小限制 0为无限制 默认KB
        queueSizeLimit :1,
        buttonText    : '图片上传', //按钮文字
        removeCompleted: true, //上传成功后的文件，是否在队列中自动删除
        overrideEvents: ['onSelectError','onSelect', 'onUploadSuccess', 'onUploadError'],//重写事件
        //选择关闭事件
        // onDialogClose:function () {},
        //返回一个错误，选择文件的时候触发          
        'onSelectError': function (file, errorCode, errorMsg) {
            var msgText = "";
            switch (errorCode) {
                case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                    //this.queueData.errorMsg = "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    msgText += "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    msgText += "文件大小超过限制" + this.settings.fileSizeLimit + "";
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    msgText += "文件大小为0";
                    break;
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    msgText += "文件格式不正确，仅限 " + this.settings.fileTypeExts;
                    break;
                default:
                    msgText += "错误代码：" + errorCode + "\n" + errorMsg;
            }
            Feng.error(msgText);
        },

        // 当选中文件时的回调函数
        'onSelect': function (file) {
            //显示上传状态
            $("#img_list").append("<div id='"+file.id+"_item' class='item col-md-2 thumbnail'>\n" +
                                        "<img src=\"../../superui/content/ui/img/loading-spinner-blue.gif\"/>\n" +
                                        "<span class=\"scale\">0%</span>\n" +
                                        "<a class=\"btn-close glyphicon glyphicon-remove\"></a>\n" +
                                    "</div>")
        },

        // 当文件上传中的回调方法
        'onUploadProgress': function (file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {
            // 设置进度条级显示的百分比
            var scale = Math.floor(bytesUploaded / bytesTotal) * 100;
            $("#"+file.id+"_item").children("span").html(scale + "%");
        },

        //检测FLASH失败调用
        'onFallback': function () {
            alert("您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。");
        },

        ////文件上传成功后的回掉方法
        'onUploadSuccess':function (file, data, response) {
            data = JSON.parse(data);
            if (data.code === 2){
                Feng.error(data.msg);
                return;
            }
            //清除加载进度比
            $("#"+file.id+"_item").children("span").remove();
            $("#"+file.id+"_item").children("img").remove();
            $("#"+file.id+"_item").children(".btn-close").attr("data-name",data.obj.fileName);
            // $("#"+file.id+"_item").append("<input type='hidden' name='' data-name='"+data.obj.fileName+"'></input>");
            $("#teacherImg").val(data.obj.fileName);
            //显示图片
            $("#"+file.id+"_item").attr("style","background-color: #ffffff;background-image:url({0}/file/getImage/{1})".format(Feng.ctxPath,data.obj.fileName));
            TeacherInfoDlg.displayUploadBtn();
        },

        //文件上传出错时触发，参数由服务端程序返回。
        'onUploadError': function (file, errorCode, errorMsg, errorString) {
            Feng.error("上传出现异常，请重新上传" + errorString);
            $("#"+file.id+"_item").remove();
        }

    });
};

//显示或隐藏上传按钮
TeacherInfoDlg.displayUploadBtn = function () {
    var length = $("#img_list .item").length;
    if (length === 1) {
        $("#file").hide();
        $("#fileTips").hide();
    }
    else {
        $("#file").show();
        $("#fileTips").show();
    }
};

//删除图片
$(document).on("click",".btn-close",function () {
    //清空教师图片
    $("#teacherImg").val("");
    //移除图片
    $(this).parent().remove();
    //移除按钮
    TeacherInfoDlg.displayUploadBtn();
});

/*$(function () {
    //初始化省、图片上传
    TeacherInfoDlg.province();
    TeacherInfoDlg.initUploadImg();
   });*/

